<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="css/normalize.css" />
    <link rel="stylesheet" href="css/index.css" />
    <script src="lib/jquery-1.12.4.min.js"></script>
  </head>
  <body>
    <div class="box1">
      呢称：<input type="text" class="input1" /><br />
      内容：<input type="text" class="input2" /><br />
      <div class="last">
        <input type="checkbox" name="unkowname" class="checkbox" /><span>匿名</span>
        <input type="button" value="发表" class="button" />
      </div>
    <div class="box2">

    </div>
      
    </div>
    <script src="lib/index.js"></script>
    <script>
      // 获取元素
      var $list = $(".cmts .list");
      var $btn = $(".reply .btn");
      var $user = $(".reply .user");
      var $editor = $(".reply .editor");
      getdata()
        function getdata() {
          $.ajax({
            url: "http://localhost:3000/db/",
            type: "GET",
            success: function (data) {
              console.log(data);
              //将得到的数据通过模板添加到页面中
              $list.html(template("tem", data));
            },
          });
        }
  
      // 添加一项新的数据到数据库中
      // 添加点击事件
      $btn.click(function () {
        var username = $user.val();
        var content = $editor.val();
        $.ajax({
          url: "http://localhost:3000/comments",
          type: "POST",
          dataType: "json",
          data: { username: username, content: content },
          success: function (data) {
            // console.log(data);
            // 制作一个模板需要的对象数据，将 data 作为数组中的项
            $list.append(template("tem", { "comments": [data] }));
            // getdata()
          }
        })
        // 清空输入
        $user.val("");
        $editor.val("");
      })
    </script>
  </body>
</html>
